function varargout = TLMergeDlg(action,varargin)

% TL_MERGE_DLG manages the user interface for TargetLink Merge block
%
% SYNTAX dlgInfo = TLMergeDlg('GetDlgInfo');
%   gets dialog info of TargetLink Merge block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLMergeDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLMergeDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLMergeDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLMergeDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLMergeDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLMergeDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.16 $
% $Date: 2011/05/12 08:08:23MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Merge';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames   = {
            'Output'; ...
            'Logging & Autoscaling'; ...
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Output'
                [sheetDims, ctrlPos] = FcnOutputCtrlPositions(commonGeom);
                
            case 'Logging & Autoscaling'
                excludedCtrls = {'keepParameter'};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);
                
            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims, ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos', commonGeom, sheetDims, bCodeComment, bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Output'
                dlgdata = ...
                    FcnCreateOutputPage(pageNum,dlgfig,dlgdata);
                
            case 'Logging & Autoscaling'
                % set bCheckLogging, because block supports bus signals
                dlgdata.pageData{pageNum}.bCheckLogging = 1;
                dlgdata = TLManageLoggingCtrls('create',pageNum,dlgfig,dlgdata);
                
            case 'Documentation'
                dlgdata = ...
                    TLManageDocCtrls('create',pageNum,dlgfig,dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');

        switch pageName
            case 'Output'
                [dlgdata,bModified] = ...
                    FcnManageOutputPage(pageNum, dlgfig, dlgdata, pageAction);
                
            case 'Logging & Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');
            
            case 'Documentation'
                [dlgdata,bModified] = ...
                    TLManageDocCtrls('callback', pageNum, dlgfig, dlgdata, pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig  = varargin{1};
        dlgdata = varargin{2};
        pageNum = varargin{3};

        pageName  = dlgdata.pageNames{pageNum};
        switch pageName
            case 'Output'
                dlgdata = FcnUpdateOutputPage(dlgdata, dlgfig, pageNum);
                
            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);
            
            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);
end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        tl_create_links_to_model('ShowComputation',dlgdata.model, 'output');

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnOutputCtrlPositions calculates positions for all controls on output page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnOutputCtrlPositions(commonGeom)

excludedCtrls = { };
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = { ...
    'Number of inputs:', 'text';
    'Initial condition:', 'text';
    'Use value of Data Dictionary variable',    'checkbox'};

[numInputsLabelSize, ...
    initialLabelSize, ...
    useDDValueCheckboxSize] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

% all controls lie in one row
% define new height for addoptGroupbox
ctrlPos.addoptGroupbox(4) = commonGeom.editHeight ...
    + commonGeom.checkboxHeight ...
    + rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;

%---------------------------------------
% 2nd row
cy = commonGeom.frameBottomEdgeBuffer;

% ddv checkbox
cx = col(1) + initialLabelSize(1) + colDelta / 3;
ctrlPos.useDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

%---------------------------------------
% 1st row
cy = cy + commonGeom.checkboxHeight + rowDelta;
% initial value label
cx = col(1);
ctrlPos.initialLabel = [cx,cy,initialLabelSize];

% initial value edit field
cx = col(1) + initialLabelSize(1) + colDelta/3;
controlWidth = col(4) - cx - colDelta/3;
ctrlPos.initialEdit = [cx, cy, controlWidth, commonGeom.editHeight];

% number of inputs label
cx = col(5);
ctrlPos.numInputsLabel = [cx,cy,numInputsLabelSize];

% number of inpus counter controls
cx = cx + ctrlPos.numInputsLabel(3) + colDelta/3;
ctrlPos.numInputsEdit = [cx,cy,ctrlPos.widthEdit(3:4)];
cx = sum(ctrlPos.numInputsEdit([1 3])) + 5;
ctrlPos.numInputsUpButton = ...
    [cx (cy + commonGeom.editHeight / 2) ctrlPos.widthDownButton(3:4)];
ctrlPos.numInputsDownButton = [cx,cy,ctrlPos.widthDownButton(3:4)];

sheetDims(2) = sheetDims(2) ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight;


%-----------------------------------------------------------------------------------------
% FcnCreateOutputPage creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateOutputPage(pageNum,dlgfig,dlgdata)

% create all controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;
pageName = dlgdata.pageNames{pageNum};
% create the addoptGroupbox which will contain further options
Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Simulation options'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

% at first create controls of initial condition and number of inputs group box
% output initial value controls
Children.initialLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Initial condition:', ...
    'Position',           ctrlPos.initialLabel);

Children.initialEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.initialEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''initialEdit'')',pageName));

% number of inputs controls
Children.numInputsLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Number of inputs:', ...
    'Position',           ctrlPos.numInputsLabel);
userData = struct('min', 2, 'max', 2^31-1);
Children.numInputsEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.numInputsEdit, ...
    'UserData',           userData, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''numInputsEdit'')',pageName));

Children.numInputsUpButton = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'pushbutton', ...
    'String',             '+', ...
    'Position',           ctrlPos.numInputsUpButton, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''numInputsUpButton'')',pageName));

Children.numInputsDownButton = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'pushbutton', ...
    'String',             '-', ...
    'Position',           ctrlPos.numInputsDownButton, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''numInputsDownButton'')',pageName));

Children.useDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.useDDValueCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''useDDValueCheckbox'')',pageName));

dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageOutputPage manage control actions of output page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageOutputPage(pageNum,dlgfig,dlgdata,action)

Children = dlgdata.pageData{pageNum}.children;
bModified = false;

switch action
    case 'initialEdit'
        initialStr = get(Children.initialEdit,'String');
        if ~isempty(initialStr)
            if strcmp(initialStr, 'ddv')
                if isempty(dlgdata.data.output.variable)
                    beep;
                else
                    dlgdata.data.output.initial = ['ddv(''', dlgdata.data.output.variable, ''')'];
                    dlgdata.data.output.useddvariablevalue = true;
                end
            else
                dlgdata.data.output.initial = initialStr;
            end
        else
            beep;
        end
        bModified = true;

    case {'numInputsEdit','numInputsUpButton','numInputsDownButton'}
        [inputs, bModified] = ...
            tl_handle_editupdown('Manage', dlgdata.data.inputs, ...
            [Children.numInputsEdit Children.numInputsUpButton Children.numInputsDownButton], ...
            Children.(action));
        inputsNum = str2num(inputs); %#ok<ST2NM>
        if bModified ...
            && ~isempty(inputsNum) && ~isequalwithequalnans(inputsNum,NaN)
            dlgdata.data.inputs = inputs;
        end

    case 'useDDValueCheckbox'
        if get(Children.useDDValueCheckbox, 'Value')
            dlgdata.data.output.initial = ['ddv(''', dlgdata.data.output.variable, ''')'];
            dlgdata.data.output.useddvariablevalue = true;
        else
            dlgdata.data.output.useddvariablevalue = false;
        end
        bModified = true;

    otherwise
        [dlgdata, bModified1] = ...
            TLManageVariableCtrls('manage', pageNum, dlgfig, dlgdata, action, 'output');
        [dlgdata, bModified2] = ...
            TLManageScalingCtrls('manage', pageNum, dlgfig, dlgdata, action, 'output');
        bModified = bModified1 | bModified2;

end


%-----------------------------------------------------------------------------------------
% FcnUpdateOutputPage updates output page
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateOutputPage(dlgdata,dlgfig,pageNum)

Children = dlgdata.pageData{pageNum}.children;

% invoke standard update methods
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'output');
[initialValue, constraint, bCompliant] = tl_get_param_constraints( ...
    dlgdata.data.output, dlgdata.extdata.output, 'initial');
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'output', constraint);

% initial condition edit
initialEditCtrlStatus = struct('enable', 'on', 'string', dlgdata.data.output.initial);
if dlgdata.data.output.useddvariablevalue
    initialEditCtrlStatus.enable = 'inactive';
end
initialEditCtrlStatus.iserror = ~bCompliant;

% get new states for bit index - edit, buttonUp and buttonDown
value = dlgdata.data.inputs;
states = tl_handle_editupdown('update', value, dlgdata, pageNum, 'numInputsEdit');
numInputsEditCtrlStatus = struct('enable', states.edit, 'string', dlgdata.data.inputs);
numInputsEditCtrlStatus.iserror = ~states.isValid;
numInputsUpButtonCtrlStatus   = struct('enable', states.up);
numInputsDownButtonCtrlStatus = struct('enable', states.down);

% status of ddv checkbox
useDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.output.variable));
useDDValueCheckboxCtrlStatus.value = dlgdata.data.output.useddvariablevalue;

% write control status of extra controls to the control's UserData propert
ctrlsList = { ...
    'initialEdit', ...
    'numInputsEdit', ...
    'numInputsUpButton', ...
    'numInputsDownButton', ...
    'useDDValueCheckbox'};
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set controls from UserData
TLManageVariableCtrls('setCtrls',pageNum,dlgfig,dlgdata);
TLManageScalingCtrls('setCtrls',pageNum,dlgfig,dlgdata);
TLSetCtrlsStatus(dlgfig,Children, ctrlsList);
